package leetcode.offer;

import leetcode.common.ListNode;

import java.util.Comparator;
import java.util.PriorityQueue;

@SuppressWarnings("all")
public class _23_合并K个升序链表 {

    /**
     * 输入：lists = [[1,4,5],[1,3,4],[2,6]]
     * 输出：[1,1,2,3,4,4,5,6]
     */
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }
        // 使用优先级队列完成链表排序
        PriorityQueue<ListNode> queue = new PriorityQueue<>(Comparator.comparingInt(o -> o.val));
        for (ListNode list : lists) {
            // 有[[]]的特殊情况
            if (list != null) {
                queue.offer(list);
            }
        }

        ListNode dummyHead = new ListNode(0);
        ListNode node = dummyHead;
        while (!queue.isEmpty()) {
            // 每次取出来的都是值最大的结点
            ListNode listNode = queue.poll();
            node.next = listNode;
            node = node.next;
            // 剩余的链表入队排序
            if (listNode != null && listNode.next != null) {
                queue.offer(listNode.next);
            }
        }
        return dummyHead.next;
    }
}
